/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.sunspotworld.demo;

import com.sun.spot.core.resources.Resources;
import com.sun.spot.ieee_802_15_4_radio.IRadioPolicyManager;
import com.sun.spot.multihop.io.j2me.radiogram.Radiogram;
import com.sun.spot.multihop.io.j2me.radiogram.RadiogramConnection;
import java.io.IOException;
import javax.microedition.io.Connector;

/**
 *
 * @author me
 */
public class RadioThreads {
    private SunSpotHostApplication hostApp;
    private RadiogramConnection xConn = null;
    private Radiogram xrg;
    private RadiogramConnection rConn = null;
    private IRadioPolicyManager rpm = (IRadioPolicyManager)Resources.lookup(IRadioPolicyManager.class);

    private Thread listenThread = new Thread() {
        public void run() {
            Radiogram rrg;
            try {
                rConn = (RadiogramConnection)Connector.open("radiogram://:46");
                rConn.setMaxBroadcastHops(0);
                rrg = (Radiogram)rConn.newDatagram(rConn.getMaximumLength());
                while (rConn != null) {
                    rrg.reset();
                    rConn.receive(rrg);
                    System.out.println("SwitchPress Signal Received");
                    if (rrg.readBoolean()) {
                        hostApp.reportSwitchPressed();
                    }
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    };

    public RadioThreads(int channel, SunSpotHostApplication host) {
        hostApp = host;
        try {
            xConn = (RadiogramConnection)Connector.open("radiogram://broadcast:45");
            xConn.setMaxBroadcastHops(0);
            xrg = (Radiogram)xConn.newDatagram(xConn.getMaximumLength());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        rpm.setChannelNumber(channel);
        listenThread.start();
    }

    public void close() {
        if (xConn != null) {
            try {
                xConn.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            xConn = null;
        }
        if (rConn != null) {
            try {
                rConn.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            rConn = null;
        }
    }

    public void sendRadioString(String theString) {
        try {
            xrg.reset();
            xrg.writeUTF(theString);
            xConn.send(xrg);
        } catch (IOException iOException) {
        }
    }

}
